import os
import platform
import subprocess
from loguru import logger
from time import sleep

class MultiDevice:
    def start_appium(self, port_number=4723):
        """
        启动appium服务器
        :return: None
        """
        self.__check_port(port_number)
        self.__connect_appium(port_number)
    def __check_port(self, port_number):
        """
        检查appium服务器端口是否被占用
        :return: None
        """
        if platform.system() == 'Linux' or platform.system() == 'Darwin':
            try:
                result = os.popen(f"lsof -i:{port_number}").read().split("\n")[1]
                os.system(f"kill -9 {result.split()[1]}")
            except Exception as e:
                    logger.info(f"端口{port_number}未被占用")
        else:
            cmd = f"netstat -ano | findstr {port_number}"
            res = os.popen(cmd).read().split("\n")[0]
            if res:
                logger.info(f"端口{port_number}已被占用")
    def __connect_appium(self, port_number):
        """
        连接appium服务器
        :return: None
        """
        device = platform.system()
        if device == 'Windows':
            cmd = f"appium -a 127.0.0.1 -p {port_number} --session-override"


        elif device == 'Darwin':
            cmd = f"start appium /b -a 127.0.0.1 -p {port_number} --session-override"
        subprocess.Popen(
                cmd,
                shell=True,
                stdout=True,
                stderr=subprocess.STDOUT,
            )
        sleep(2)
    def stop_appium(self, port_number=4723):
        """
        停止指定端口的appium服务器
        :param port_number: 端口号，默认4723
        :return: None
        """
        system = platform.system()
        if system == 'Windows':
            # Windows系统
            cmd_find = f"netstat -ano | findstr {port_number}"
            try:
                result = os.popen(cmd_find).read().strip()
                if result:
                    # 提取PID
                    lines = result.split('\n')
                    for line in lines:
                        if 'LISTENING' in line:
                            pid = line.split()[-1]
                            # 杀死进程
                            os.system(f"taskkill /F /PID {pid}")
                            logger.info(f"Windows系统: 已停止端口 {port_number} 的Appium进程 (PID: {pid})")
                            return
                logger.info(f"Windows系统: 端口 {port_number} 未被占用")
            except Exception as e:
                logger.error(f"停止Appium时出错: {e}")

        elif system == 'Darwin' or system == 'Linux':
            # macOS 或 Linux 系统
            cmd_find = f"lsof -i :{port_number}"
            try:
                result = os.popen(cmd_find).read().strip()
                if result:
                    lines = result.split('\n')
                    if len(lines) > 1:
                        # 第一行是标题，第二行是进程信息
                        pid = lines[1].split()[1]
                        os.system(f"kill -9 {pid}")
                        logger.info(f"{system}系统: 已停止端口 {port_number} 的Appium进程 (PID: {pid})")
                        return
                logger.info(f"{system}系统: 端口 {port_number} 未被占用")
            except Exception as e:
                logger.error(f"停止Appium时出错: {e}")
        else:
            logger.error(f"不支持的操作系统: {system}")

